from vnpy.event import EventEngine

from vnpy.trader.engine import MainEngine
from vnpy.feeds.datamanager import DataManager

import tushare as ts
import datetime
import pandas as pd

today = datetime.date.today()
# print(today)

# formatted_today = today.strftime('%Y%m%d')
# print(formatted_today)

import tushare as ts

# 初始化pro接口
# pro = ts.pro_api('1ec02d45c79943f2e88da92478a95c9e7dcf361dfa73bc518a1283de')

# 拉取数据
# df = pro.fut_mapping(**{
#     "ts_code": "",
#     "trade_date": today.strftime('%Y%m%d'),
#     "start_date": "",
#     "end_date": "",
#     "limit": "",
#     "offset": ""
# }, fields=[
#     "ts_code",
#     "trade_date",
#     "mapping_ts_code"
# ])
# print(df)
# print(df.head(1))
import json

#
# import vnpy_mongodb


# col_stock_basic = db_stock["stock_basic"]
# col_stock_watchlist = db_stock["stock_watchlist"]
# col_fut_watchlist = db_fut["fut_watchlist"]
# col_fut_basic = db_fut["fut_basic"]
# fut_watchlist = []
# exchange = ["CZCE","SHFE","DCE"]
# , fields='ts_code,symbol,name,list_date,delist_date'
# for x in exchange:
#     df = pro.fut_basic(exchange=x, fut_type='1')
#     col_fut_basic.insert_many(json.loads(df.T.to_json()).values())
#     print(df.head())

import pymongo


# def db_conect(self, db_name="test", col_name="test"):
#     my_client = pymongo.MongoClient("mongodb://localhost:27017/")
#     db = my_client[db_name]
#     col = my_client[col_name]
#     return col


# df = pro.opt_basic(**{
#     "ts_code": "SA.ZCE",
#     "exchange": "",
#     "call_put": "",
#     "offset": "",
#     "limit": ""
# }, fields=[
#     "ts_code",
#     "exchange",
#     "name",
#     "per_unit",
#     "opt_code",
#     "opt_type",
#     "call_put",
#     "exercise_type",
#     "exercise_price",
#     "s_month",
#     "maturity_date",
#     "list_price",
#     "list_date",
#     "delist_date",
#     "last_edate",
#     "last_ddate",
#     "quote_unit",
#     "min_price_chg"
# ])
# df = pro.fut_mapping(ts_code='SA.ZCE')
# df = pro.fut_mapping(ts_code='TF.CFX')
# print(df)
# SA2209.ZCE
# fut_code = ["AG","RM", "FU", "C", "SA", "FG", "RB", "y", "M", "MA"]
#
# for x in fut_code:
#     y = col_fut_basic.find_one({'fut_code': x, "name": {'$regex': '主力'}}, {"ts_code", "symbol", "name", "list_date", "delist_date"})
#     # col_fut_watchlist.insert_one(y)
#     print(y)

# df = pro.query('stock_basic', exchange='SSE', ts_code='', list_status='L', fields='ts_code,symbol,name,exchange,industry,list_date')

# stock_basic.insert_many(json.loads(df.T.to_json()).values())
# df = pro.query('stock_basic', exchange='SZSE', ts_code='', list_status='L', fields='ts_code,symbol,name,exchange,industry,list_date')

#

def db_insert_many(self, db=None, df=None):
    db.insert_many(json.loads(df.T.to_json()).values())


# x = stock_basic.find_one()
# print(x)
# stock_basic.create_index([('symbol', pymongo.ASCENDING)],  unique=True)
# sorted(list(stock_basic.index_information()))

# df = pro.query('stock_basic', exchange='SSE', ts_code='600000', list_status='L', fields='ts_code,symbol,name,exchange,industry,list_date')
# print(df)
# stock_basic.insert_one(json.loads(df.T.to_json()).values())

# stock = stock_basic.find({'industry': '银行'})
# for x in stock:
#     print(x)

# print(stock_basic.count_documents({}))
# db_watchlist.create_index([('symbol', pymongo.ASCENDING)],  unique=True)
watchlist = ['600089', '002129', '600438', '002459', '300450', '601012', '300274']

#
# for x in watchlist:
#     _stock = stock_basic.find_one({'symbol': x})
#     # print(_stock)
#     try:
#         db_watchlist.insert_one(_stock)
#     except:
#         print("重复插入", x)


import hs_udata as udata

# import  vnpy_udata

udata.set_token(token='fVd9liTbWbGATOCt2TMXxGL4RIOkQrDJNm0Fh9eA_9Efy670eyC6AMQPUH7_gcUy')
import pandas
# df = udata.stock_list(fields="secu_code,secu_abbr,secu_market,hs_code")
# df = udata.fut_quote_minute(en_prod_code="SA2209.CZC")

# df = udata.fut_quote_minute(en_prod_code="600000.SH", begin_date="2021-05-01", end_date="2021-05-20")
# df: pandas.DataFrame = udata.stock_quote_minutes(en_prod_code='600000.SH', begin_date='20190707', end_date='20220706')

# df = udata.stock_quote_minutes(en_prod_code="000001.SZ",  begin_date="20210805", end_date="20210809")
# df = udata.stock_quote_minutes(en_prod_code="600000.SH",  begin_date="2020-08-05", end_date="20200905")
# df = udata.fut_list()
# pd.DataFrame.to_csv()
# df = udata.stock_quote_minutes(en_prod_code='600000.SH')
# print(df.head())

#
# data = udata.trading_calendar(secu_market='83')
# data = udata.company_profile(en_prod_code="600570.SH")
# print(data.head())

# data = udata.stock_quote_daily(en_prod_code="600570.SH", trading_date="20210810")
# print(data.head())

# data = udata.stock_quote_minutes(en_prod_code="000001.SZ", begin_date="20220705", end_date="20220705")

# for x in watchlist
# data = udata.profitability(en_prod_code="600570.SH",report_date="2020-12-31", fields="prod_code,roe")
# print(data)

# stock = db_watchlist.find()

# print(stock)

import vnpy_udata

import pymongo
import vnpy_mongodb

# data = udata.fut_list()
# print(data.head())

# data = udata.fut_contract_type(exchange_code='15', fields="contract_month,fut_option_code")
# print(data.head())
# data = udata.fut_quote_minute(en_prod_code="SC2109.INE"  , begin_date="2021-05-01", end_date="2021-05-20")
# print(data.head())

# import vnpy.trader.database as db
#
# vdb = db.get_database()
# print (vdb)
# vdb.load_bar_data();

import vnpy_datamanager as datamanager

# vdb.download_bar_data("symbol", exchange, start)
import vnpy_tushare
import vnpy_mongodb

# datamanager.

from vnpy.trader.constant import Interval, Exchange
from vnpy.trader.database import DB_TZ

symbol = '600000'
exchange = Exchange('SSE')
interval = Interval("1m")

start = datetime.datetime(2022, 7, 17)
# start = datetime(start_date.year(), start_date.month(), start_date.day())
start = DB_TZ.localize(start)


# dm = datamanager.ManagerEngine()

# count = dm.download_bar_data(symbol, exchange, interval, start)
# print(count)


def fut_list():
    from hs_udata import set_token, fut_list
    udata.set_token(token='fVd9liTbWbGATOCt2TMXxGL4RIOkQrDJNm0Fh9eA_9Efy670eyC6AMQPUH7_gcUy')
    data = fut_list()
    print(data.head())


def fut_contract_type():
    from hs_udata import set_token, fut_contract_type
    set_token(token='fVd9liTbWbGATOCt2TMXxGL4RIOkQrDJNm0Fh9eA_9Efy670eyC6AMQPUH7_gcUy')
    data = fut_contract_type()
    print(data.head())


fut_list()


# fut_contract_type()
